package com.sanpu.kxe.business.main.fragment;

import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseFragment;
import com.sanpu.kxe.business.main.bean.InviteMakeMoneyOutput;
import com.sanpu.kxe.business.main.bean.RebateTotalOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.contract.EarningsContract;
import com.sanpu.kxe.business.main.presenter.EarningsPresenter;
import com.sanpu.kxe.business.main.provider.MainOpenProvider;
import com.sanpu.kxe.business.main.view.AuthorizationActivity;
import com.sanpu.kxe.business.main.view.ZeroPurchActivity;
import com.sanpu.kxe.business.member.provider.IMemberProvider;
import com.sanpu.kxe.business.trade.provider.ITradeProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.jump.eventbus.RefreshBalanceEvent;
import com.sanpu.kxe.jump.eventbus.RefreshEarningsEvent;
import com.sanpu.kxe.module.dialog.ShareEarningsDialog;
import com.sanpu.kxe.module.widget.NumberRunningTextView;
import com.sanpu.kxe.module.widget.VerticalSwipeRefreshLayout;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.SystemBarHelper;
import com.tencent.mm.opensdk.modelbiz.JumpToBizProfile;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：新收益页面
 * Created by 薛勇军 on 2018/10/17.
 */

public class EarningsFragment extends BaseFragment implements EarningsContract.View {

    @Bind(R.id.amount)
    NumberRunningTextView vAmount;
    @Bind(R.id.swipeRefreshLayout)
    VerticalSwipeRefreshLayout vSwipeRefreshLayout;
    @Bind(R.id.headerView)
    RelativeLayout headerView;

    @Bind(R.id.amountPwdIv)
    ImageView amountPwdIv;
    @Bind(R.id.showIv)
    ImageView showIv;
    @Bind(R.id.mySqs)
    LinearLayout mySqsLl;

    private String withdrawMoney = "0";

    private ShareEarningsDialog vEarningsDialog;

    private EarningsContract.Presenter mPresenter;

    private List<InviteMakeMoneyOutput> mInviteMakeMoneyOutputs = new ArrayList<>();

    private boolean refreshInvite = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisible()) {
            try {
                if (vAmount != null)
                    vAmount.setContent(withdrawMoney);
                if (mPresenter != null)
                    mPresenter.getRebateTotal();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_earnings;
    }

    @Override
    protected void initView() {
        super.initView();
        int barHeight = SystemBarHelper.getStatusBarHeight(getContext());
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) headerView.getLayoutParams();
        params.setMargins(0, barHeight, 0, 0);
        headerView.setLayoutParams(params);

        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null && centerOutput.isAuthorization()) {
            mySqsLl.setVisibility(View.VISIBLE);
        } else {
            mySqsLl.setVisibility(View.GONE);
        }

        mPresenter = new EarningsPresenter(this);
        mPresenter.getRebateTotal();
        mPresenter.inviteMakeMoney();
    }

    @Override
    protected void initData() {
        super.initData();
        boolean showTotal = CacheManage.getInstance().getCache(CacheModel.EARNING_TOTAL_MONEY, false);
        if (!showTotal) {
            showIv.setImageResource(R.drawable.ic_home_head_show);
            amountPwdIv.setVisibility(View.GONE);
            vAmount.setVisibility(View.VISIBLE);
        } else {
            showIv.setImageResource(R.drawable.ic_home_head_close);
            amountPwdIv.setVisibility(View.VISIBLE);
            vAmount.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        vSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getRebateTotal();
            }
        });
        showIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean showTotal = CacheManage.getInstance().getCache(CacheModel.EARNING_TOTAL_MONEY, false);
                if (!showTotal) {
                    showIv.setImageResource(R.drawable.ic_home_head_close);
                    amountPwdIv.setVisibility(View.VISIBLE);
                    vAmount.setVisibility(View.GONE);
                } else {
                    showIv.setImageResource(R.drawable.ic_home_head_show);
                    amountPwdIv.setVisibility(View.GONE);
                    vAmount.setVisibility(View.VISIBLE);
                }
                CacheManage.getInstance().saveCache(CacheModel.EARNING_TOTAL_MONEY, !showTotal);
            }
        });
    }

    @OnClick({R.id.withdrawRtv, R.id.mySyxq, R.id.myTdmx, R.id.myFxzq, R.id.myXekt, R.id.myXesck, R.id.myXecz, R.id.mySqs})
    public void onClick(View view) {
        try {
            switch (view.getId()) {
//                case R.id.myPromote:
//                    IMemberProvider memberProvider = PublicProviderUtil.getProvider(IMemberProvider.class);
//                    if (memberProvider != null) {
//                        memberProvider.openMemberSpreadActivity(getContext());
//                    }
//                    break;
//                case R.id.shareReg:
//                    MainOpenProvider.getInstance().openInviteFriendsActivity(getContext());
//                    break;
//                case R.id.promotePoster:
//                    MainOpenProvider.getInstance().openPromotePosterActivity(getContext());
//                    break;
//                case R.id.offlineMaterial:
////                    MainOpenProvider.getInstance().openPushMaterialActivity(getContext());
//                    MainOpenProvider.getInstance().openBrowserX5Activity(getContext(), UrlConstants.OPERATE_HELP, true);
//                    break;
//                case R.id.myQrcode:
//                    MainOpenProvider.getInstance().openMyQrcodeActivity(getContext());
//                    break;
                case R.id.mySyxq:
                    ITradeProvider tradeProvider = PublicProviderUtil.getProvider(ITradeProvider.class);
                    if (tradeProvider != null) {
                        tradeProvider.openRebTotalListActivity(getContext());
                    }
                    break;
                case R.id.myTdmx:
                    IMemberProvider memberProvider = PublicProviderUtil.getProvider(IMemberProvider.class);
                    if (memberProvider != null) {
                        memberProvider.openMemberTeamListActivity(getContext());
                    }
                    break;
                case R.id.withdrawRtv:
                    mPresenter.withdrawSigning(withdrawMoney);
                    break;
                case R.id.myFxzq:
                    if (refreshInvite) {
                        refreshInvite = false;
                        vEarningsDialog = new ShareEarningsDialog(getContext(), mInviteMakeMoneyOutputs);
                    } else {
                        if (vEarningsDialog == null) {
                            vEarningsDialog = new ShareEarningsDialog(getContext(), mInviteMakeMoneyOutputs);
                        } else {
                            vEarningsDialog.show();
                        }
                    }
                    break;
                case R.id.myXekt:
                    onWechatGzhClick();
                    break;
                case R.id.myXesck:
                    MainOpenProvider.getInstance().openMaterialLibraryActivity(getContext());
                    break;
                case R.id.myXecz:
                    IntentTool.startActivity(getContext(), ZeroPurchActivity.class);
                    break;
                case R.id.mySqs:
                    IntentTool.startActivity(getContext(), AuthorizationActivity.class);
                    break;
//                case R.id.myProfit:
//                    ITradeProvider tProvider = PublicProviderUtil.getProvider(ITradeProvider.class);
//                    if (tProvider != null) {
//                        tProvider.openMyProfitActivity(getContext());
//                    }
//                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void onWechatGzhClick() {
        IWXAPI api = WXAPIFactory.createWXAPI(getActivity(), CommonConfig.WX_APPID, false);

        if (api.isWXAppInstalled()) {
            JumpToBizProfile.Req req = new JumpToBizProfile.Req();
            req.toUserName = "gh_275957ed8524"; // 公众号原始ID
            req.extMsg = "sss";
            req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE; // 普通公众号
            api.sendReq(req);
        }else{
            Toast.makeText(getActivity(), "微信未安装", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showRebateTotalView(RebateTotalOutput output) {
        if (vSwipeRefreshLayout.isRefreshing()) {
            vSwipeRefreshLayout.setRefreshing(false);
        }
        if (output == null) {
            output = CacheManage.getInstance().getCache(CacheModel.REBATETOTAL);
        }
        if (output != null) {
            if (output.getWithdrawAmt() != null) {
                withdrawMoney = output.getWithdrawAmt().toPlainString();
                vAmount.setContent(withdrawMoney);
            }
        }
    }

    @Override
    public void showInviteMakeMoneyData(List<InviteMakeMoneyOutput> inviteMakeMoneyOutputs) {
        if (inviteMakeMoneyOutputs != null) {
            refreshInvite = true;
            mInviteMakeMoneyOutputs.clear();
            mInviteMakeMoneyOutputs.addAll(inviteMakeMoneyOutputs);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshProfits(RefreshBalanceEvent event) {
        if (event != null) {
            mPresenter.getRebateTotal();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEarnings(RefreshEarningsEvent event) {
        if (event != null) {
            if (event.isAuthorization()) {
                mySqsLl.setVisibility(View.VISIBLE);
            } else {
                mySqsLl.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(EarningsContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
